import { useMemo } from 'react'
import {
  useNavigate,
  useLocation,
  useParams,
  useSearchParams,
  createSearchParams,
} from 'react-router-dom'

const useRouter = () => {
  const params = useParams()
  const navigate = useNavigate()
  const location = useLocation()
  const [searchParams, setSearchParams] = useSearchParams()
  const setQuery = (params: Record<string, string>) => createSearchParams(params).toString()

  return useMemo(() => {
    return {
      navigate,
      setSearchParams,
      setQuery,
      location,
      pathname: location.pathname,

      // merge params and query into single 'query' object.
      query: {
        ...Object.fromEntries(new URLSearchParams(searchParams)),
        ...params,
      },
    }
  }, [params, location, searchParams, setSearchParams, navigate])
}

export default useRouter
